package com.zzh.takeoutapp.activity;

import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.widget.AutoCompleteTextView;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDAbstractLocationListener;
import com.baidu.location.BDLocation;
import com.baidu.mapapi.animation.Animation;
import com.baidu.mapapi.animation.Transformation;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.DotOptions;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdate;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.Marker;
import com.baidu.mapapi.map.MarkerOptions;
import com.baidu.mapapi.map.MyLocationData;
import com.baidu.mapapi.map.OverlayOptions;
import com.baidu.mapapi.model.LatLng;
import com.baidu.mapapi.search.core.PoiInfo;
import com.baidu.mapapi.search.core.SearchResult;
import com.baidu.mapapi.search.geocode.GeoCodeResult;
import com.baidu.mapapi.search.geocode.GeoCoder;
import com.baidu.mapapi.search.geocode.OnGetGeoCoderResultListener;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeOption;
import com.baidu.mapapi.search.geocode.ReverseGeoCodeResult;
import com.baidu.mapapi.search.poi.OnGetPoiSearchResultListener;
import com.baidu.mapapi.search.poi.PoiCitySearchOption;
import com.baidu.mapapi.search.poi.PoiDetailResult;
import com.baidu.mapapi.search.poi.PoiIndoorResult;
import com.baidu.mapapi.search.poi.PoiResult;
import com.baidu.mapapi.search.poi.PoiSearch;
import com.zzh.takeoutapp.R;
import com.zzh.takeoutapp.adapter.AddLocationAdapter;
import com.zzh.takeoutapp.adapter.OnRecyleItemClick;
import com.zzh.takeoutapp.base.BaseActivity;
import com.zzh.takeoutapp.entity.SelectShopBean;
import com.zzh.takeoutapp.map.LocationService;
import com.zzh.takeoutapp.utils.ToolBarHelper;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Created by Administrator on 2018/8/1.
 */

public class AddLocationActivity extends BaseActivity implements OnGetPoiSearchResultListener {
    @Bind(R.id.toolbar)
    Toolbar tbToolbar;
    @Bind(R.id.recyclerView)
    RecyclerView recyclerView;
    @Bind(R.id.tv_city)
    TextView tv_city;
    private MapView mMapView;
    private PoiSearch mPoiSearch = null;
    private BaiduMap mBaiduMap = null;
    private AutoCompleteTextView keyWorldsView = null;
    private int loadIndex = 0;
    private boolean isFirstLoc = true;
    private MyLocationListener mListener = new MyLocationListener();
    private LocationService locationService;
    private Marker mMarkerF;
    private Point mScreenCenterPoint;
    private LatLng llF;
    private BitmapDescriptor bdF = BitmapDescriptorFactory.fromResource(R.drawable.icon_markf);
    private AddLocationAdapter addLocationAdapter;
    private List<SelectShopBean> selectShopBeans;//定位的地址

    @Override
    public void setContent() {
        setContentView(R.layout.activity_add_location);
        ButterKnife.bind(this);
    }

    @Override
    public void initComponent() {
        ToolBarHelper.setTitleAndBackAndText(this, tbToolbar, "新增收货地址");
        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        selectShopBeans = new ArrayList<>();
        // 初始化搜索模块，注册搜索事件监听
        mPoiSearch = PoiSearch.newInstance();
        mPoiSearch.setOnGetPoiSearchResultListener(this);
        // 初始化建议搜索模块，注册建议搜索事件监听
        keyWorldsView = (AutoCompleteTextView) findViewById(R.id.searchkey);
        mMapView = (MapView) findViewById(R.id.map_View);
        mBaiduMap = mMapView.getMap();
    }

    @Override
    public void setListener() {
        /**
         * 当输入关键字变化时，动态更新建议列表
         */
        keyWorldsView.addTextChangedListener(new TextWatcher() {

            @Override
            public void afterTextChanged(Editable arg0) {

            }

            @Override
            public void beforeTextChanged(CharSequence arg0, int arg1,
                                          int arg2, int arg3) {

            }

            @Override
            public void onTextChanged(CharSequence cs, int arg1, int arg2,
                                      int arg3) {
                if (cs.length() <= 0) {
                    return;
                }
                if (selectShopBeans != null) {
                    selectShopBeans.addAll(selectShopBeans);
                }
                String keystr = keyWorldsView.getText().toString();
                mPoiSearch.searchInCity((new PoiCitySearchOption())
                        .city(tv_city.getText().toString()).keyword(keystr).pageNum(loadIndex));

            }
        });

        mBaiduMap.setOnMapLoadedCallback(new BaiduMap.OnMapLoadedCallback() {
            @Override
            public void onMapLoaded() {
                initOverlay();
            }
        });

        mBaiduMap.setOnMapStatusChangeListener(new BaiduMap.OnMapStatusChangeListener() {
            @Override
            public void onMapStatusChangeStart(MapStatus status) {

            }

            @Override
            public void onMapStatusChangeStart(MapStatus status, int reason) {

            }

            @Override
            public void onMapStatusChange(MapStatus status) {

            }

            @Override
            public void onMapStatusChangeFinish(MapStatus status) {
                if (null == mMarkerF) {
                    return;
                }
                LatLng point = new LatLng(status.target.latitude, status.target.longitude);
                getdata(point);
               /* mMarkerF.setAnimation(getTransformationPoint());
                mMarkerF.startAnimation();*/
            }
        });
    }

    /**
     * 初始化Overlay
     */
    public void initOverlay() {
        if (null != mBaiduMap.getMapStatus()) {
            llF = mBaiduMap.getMapStatus().target;
            mScreenCenterPoint = mBaiduMap.getProjection().toScreenLocation(llF);
            MarkerOptions ooF = new MarkerOptions().position(llF).icon(bdF).perspective(true)
                    .fixedScreenPosition(mScreenCenterPoint);
            mMarkerF = (Marker) (mBaiduMap.addOverlay(ooF));
        }
        MapStatusUpdate msu = MapStatusUpdateFactory.zoomTo(12.0f);
        mBaiduMap.setMapStatus(msu);

    }


    /**
     * 创建平移坐标动画
     */
    private Animation getTransformationPoint() {

        if (null != mScreenCenterPoint) {
            Point pointTo = new Point(mScreenCenterPoint.x, mScreenCenterPoint.y - 100);
            Transformation mTransforma = new Transformation(mScreenCenterPoint, pointTo, mScreenCenterPoint);
            mTransforma.setDuration(500);
            mTransforma.setRepeatMode(Animation.RepeatMode.RESTART);//动画重复模式
            mTransforma.setRepeatCount(1);//动画重复次数
            mTransforma.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart() {
                }

                @Override
                public void onAnimationEnd() {
                }

                @Override
                public void onAnimationCancel() {
                }

                @Override
                public void onAnimationRepeat() {

                }
            });
            return mTransforma;
        }

        return null;
    }

    @Override
    public void onAfterInit() {
    }

    @Override
    public void onStart() {
        super.onStart();
        locationService = new LocationService(this);
        locationService.registerListener(mListener);
        locationService.setLocationOption(locationService.getDefaultLocationClientOption());
        locationService.start();// 定位SDK
    }

    public class MyLocationListener extends BDAbstractLocationListener {
        @Override
        public void onReceiveLocation(BDLocation bdLocation) {
            if (bdLocation == null || mMapView == null) {
                return;
            }
            MyLocationData locData = new MyLocationData.Builder().accuracy(bdLocation.getRadius())
                    // 此处设置开发者获取到的方向信息，顺时针0-360
                    .direction(bdLocation.getDirection()).latitude(bdLocation.getLatitude())
                    .longitude(bdLocation.getLongitude()).build();
            tv_city.setText(bdLocation.getCity());
            // 设置定位数据
            mBaiduMap.setMyLocationData(locData);
            //地图SDK处理
            if (isFirstLoc) {
                isFirstLoc = false;
                LatLng ll = new LatLng(bdLocation.getLatitude(),
                        bdLocation.getLongitude());
                MapStatus.Builder builder = new MapStatus.Builder();
                builder.target(ll).zoom(18.0f);
                mBaiduMap.animateMapStatus(MapStatusUpdateFactory.newMapStatus(builder.build()));
            }
            LatLng point = new LatLng(bdLocation.getLatitude(), bdLocation.getLongitude());
            OverlayOptions dotOption = new DotOptions().center(point).color(0xAAFF0000);
            mBaiduMap.addOverlay(dotOption);
            getdata(point);
        }
    }

    private void getdata(LatLng ll) {
        GeoCoder geoCoder = GeoCoder.newInstance();
        OnGetGeoCoderResultListener listener = new OnGetGeoCoderResultListener() {
            @Override
            public void onGetReverseGeoCodeResult(ReverseGeoCodeResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                    return;
                }
                List<PoiInfo> poiList = result.getPoiList();
                setAdapter(poiList);
                locationService.stop();
            }

            @Override
            public void onGetGeoCodeResult(GeoCodeResult result) {
                if (result == null || result.error != SearchResult.ERRORNO.NO_ERROR) {
                }
            }
        };
        geoCoder.setOnGetGeoCodeResultListener(listener);
        geoCoder.reverseGeoCode(new ReverseGeoCodeOption().location(ll));
    }

    @Override
    public void onStop() {
        locationService.unregisterListener(mListener); //注销掉监听
        locationService.stop(); //停止定位服务
        super.onStop();
    }

    @Override
    protected void onPause() {
        super.onPause();
        // activity 暂停时同时暂停地图控件
        mMapView.onPause();
    }

    @Override
    protected void onResume() {
        super.onResume();
        // activity 恢复时同时恢复地图控件
        mMapView.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // activity 销毁时同时销毁地图控件
        MapView.setMapCustomEnable(false);
        mMapView.onDestroy();
        mMapView = null;
        mPoiSearch.destroy();
        mMarkerF.cancelAnimation();
        bdF.recycle();
    }

    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
    }

    @Override
    protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
    }

    /**
     * 获取POI搜索结果，包括searchInCity，searchNearby，searchInBound返回的搜索结果
     *
     * @param result
     */
    public void onGetPoiResult(PoiResult result) {
        if (result == null || result.error == SearchResult.ERRORNO.RESULT_NOT_FOUND) {
            Toast.makeText(this, "未找到结果", Toast.LENGTH_LONG)
                    .show();
            return;
        }
        if (result.error == SearchResult.ERRORNO.NO_ERROR) {
            List<PoiInfo> poiList = result.getAllPoi();
            setAdapter(poiList);
            return;
        }
    }

    private void setAdapter(List<PoiInfo> poiList) {
        addLocationAdapter = new AddLocationAdapter(poiList, AddLocationActivity.this);
        recyclerView.setAdapter(addLocationAdapter);
        addLocationAdapter.notifyDataSetChanged();
        addLocationAdapter.addOnRecyleItemClick(new OnRecyleItemClick() {
            @Override
            public void onItemClick(View v, Object o, int position) {
                Intent intent = new Intent();
                intent.putExtra("address", addLocationAdapter.getItem(position).address);
                intent.putExtra("name", addLocationAdapter.getItem(position).name);
                intent.putExtra("latitude", String.valueOf(addLocationAdapter.getItem(position).location.latitude));
                intent.putExtra("longitude", String.valueOf(addLocationAdapter.getItem(position).location.longitude));
                setResult(1, intent);
                finish_Activity();
            }
        });
    }

    /**
     * 获取POI详情搜索结果，得到searchPoiDetail返回的搜索结果
     *
     * @param result
     */

    public void onGetPoiDetailResult(PoiDetailResult result) {
        if (result.error != SearchResult.ERRORNO.NO_ERROR) {
            Toast.makeText(this, "抱歉，未找到结果", Toast.LENGTH_SHORT)
                    .show();
        } else {
            Toast.makeText(this, result.getName() + ": " + result.getAddress(), Toast.LENGTH_SHORT)
                    .show();
        }
    }

    @Override
    public void onGetPoiIndoorResult(PoiIndoorResult poiIndoorResult) {

    }
}
